﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Security;
using System.Data.SqlClient;
using System.Data;
using SalePartial.Utility;
using SalePartial.Model;
using XunPan.Web.Globals;

namespace SalePartial.BLL
{
    public class ModerateBLL
    {

        /// <summary>
        /// 公共询盘分配操作
        /// </summary>
        /// <param name="xpid">询盘标识符</param>
        /// <param name="qid">报价标识符</param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static int AssignXP(string xpid, string qid)
        {
            int functionReturnValue = 0;

            try
            {

                if (GlobalUtility.IsValidGuid(xpid) && GlobalUtility.IsValidGuid(qid))
                {
                    XPInquiry xpInquiry = new XPInquiry();
                    XPInquiryInfo inquiry = xpInquiry.GetXPInquiry(new Guid(xpid));
                    XPQuote xpQuote = new XPQuote();
                    XPQuoteInfo quote = xpQuote.GetXPQuote(new Guid(qid));

                    //设置事件关联状态
                    XPInquiryEvent xpInqu = new XPInquiryEvent();
                    DataSet ds = xpInqu.SelectByInquiryID(new Guid(xpid));
                    if (ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
                    {
                        functionReturnValue = -1;
                        return functionReturnValue;

                    }
                    else
                    {
                        //DataTable dt = ds.Tables[0];
                        //DataRow[] dr = dt.Select("[QuoteID] = " + qid);
                        //if (dr.Length == 1)
                        //{
                        //    //section left here to add event status updating in future

                        //    //Dim ievent As New XPInquiryEvent(New Guid(dr(0).Item("EventID").ToString))

                        //    //ievent.EventStatus=
                        //}
                        //else
                        //{
                        //    return -2;
                        //    return functionReturnValue;
                        //}

                    }

                    var _with1 = quote;
                    //设置报价状态

                    _with1.QuoteStatus = _with1.QuoteStatus.Remove(3, 1);
                    _with1.QuoteStatus = _with1.QuoteStatus.Insert(3, "1");
                    //设置反馈状态
                    //QuoteStatus的第6位(供应商)反馈状态用，QuoteStatus的第7位(采购商)反馈状态用
                    //_with1.QuoteStatus = _with1.QuoteStatus.Remove(5, 1);
                    //_with1.QuoteStatus = _with1.QuoteStatus.Insert(5, FeedbackStatus.NoAction.GetHashCode().ToString());
                    //_with1.QuoteStatus = _with1.QuoteStatus.Remove(6, 1);
                    //_with1.QuoteStatus = _with1.QuoteStatus.Insert(6, FeedbackStatus.Required.GetHashCode().ToString());
                    xpQuote.Update(_with1);


                    //设置询盘状态
                    inquiry.InquiryStatus = inquiry.InquiryStatus.Remove(4, 1);
                    inquiry.InquiryStatus = inquiry.InquiryStatus.Insert(4, "1");
                    xpInquiry.Update(inquiry);

                    ds = xpInqu.SelectDynamic(string.Format("[VendorCompanyID] = '{0}' AND [InquiryID] = '{1}'", quote.CompanyID, quote.InquiryID), "");

                    DataTable dt = ds.Tables[0];
                    if (ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
                    
                        for(int i = 0;i<ds.Tables[0].Rows.Count;i++)
                        {
                            XPInquiryEventInfo xpevent = xpInqu.GetXPInquiryEvent(new Guid(ds.Tables[0].Rows[i]["EventID"].ToString()));

                            xpevent.EventStatus = xpevent.EventStatus.Remove(1, 1);
                            xpevent.EventStatus = xpevent.EventStatus.Insert(1, "1");
                            xpInqu.Update(xpevent);
                        }
                    

                    //发送系统邮件
                    MembershipUser userInfo = Membership.GetUser(quote.UserID);
                    if (userInfo != null)
                    {
                        MailSendUtility.SyncSendMail(userInfo.Email, "零部件环球资源网--您的报价被授盘", "您的报价被授盘");
                    }
                    //消息
                    XPNotificationInfo msg = new XPNotificationInfo();
                    XPNotification xpNotifi = new XPNotification();

                    msg.CreateUserID = inquiry.UserID;
                    msg.Status = "0100000";
                    msg.CreateDate = DateTime.Now;

                    msg.RecipientUserID = quote.UserID;
                    msg.Attachment = "";
                    msg.BodyText = "您的报价被授盘" ;
                    msg.SendDate = DateTime.Now;
                    msg.Title = "零部件环球资源网--您的报价被授盘";

                    msg.ContentType = 0;
                    xpNotifi.Insert(msg);


                }

            }
            catch (Exception ex)
            {
                return -1;

            }
            functionReturnValue = 1;
            return functionReturnValue;
        }
        /// <summary>
        /// 报价事务提交状态更新操作
        /// </summary>
        /// <param name="xpid"></param>
        /// <param name="qid"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static int SubmitQuote(string xpid, string qid)
        {
            int functionReturnValue = 0;

            try
            {
                if (GlobalUtility.IsValidGuid(xpid) && GlobalUtility.IsValidGuid(qid))
                {
                    XPInquiry xpInquiry = new XPInquiry();
                    XPInquiryInfo inquiry = xpInquiry.GetXPInquiry(new Guid(xpid));
                    XPQuote xpQuote = new XPQuote();
                    XPQuoteInfo quote = xpQuote.GetXPQuote(new Guid(qid));

                    //设置事件关联状态
                    XPInquiryEvent xpInqu = new XPInquiryEvent();
                    DataSet ds = xpInqu.SelectByInquiryID(new Guid(xpid));
                    if (ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
                    {
                        return -1;
                        return functionReturnValue;

                    }
                    else
                    {
                        DataTable dt = ds.Tables[0];
                        DataRow[] dr = dt.Select("[QuoteID] = " + qid);
                        if (dr.Length == 1)
                        {
                            //section left here to add event status updating in future

                            XPInquiryEventInfo ievent = xpInqu.GetXPInquiryEvent(new Guid(dr[0]["EventID"].ToString()));

                            ievent.EventStatus = ievent.EventStatus.Remove(2, 1);
                            ievent.EventStatus = ievent.EventStatus.Insert(2, "1");
                        }
                        else
                        {
                            return -2;
                            return functionReturnValue;
                        }

                    }

                    var _with2 = quote;
                    //设置报价提交状态
                    _with2.QuoteStatus = _with2.QuoteStatus.Remove(1, 1);
                    _with2.QuoteStatus = _with2.QuoteStatus.Insert(1, "1");
                    xpQuote.Update(_with2);


                    //设置询盘状态()
                    inquiry.InquiryStatus = inquiry.InquiryStatus.Remove(3, 1);
                    inquiry.InquiryStatus = inquiry.InquiryStatus.Insert(3, "1");
                    xpInquiry.Update(inquiry);

                    //发送系统邮件


                }

            }
            catch (Exception ex)
            {
                return -1;

            }

            return 1;
            return functionReturnValue;
        }

        /// <summary>
        /// 查看报价
        /// </summary>
        /// <param name="qid"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static int ReadQuote(string qid)
        {

            try
            {

                if (GlobalUtility.IsValidGuid(qid))
                {
                    XPQuote xpQuote = new XPQuote();
                    XPQuoteInfo quote = xpQuote.GetXPQuote(new Guid(qid));

                    var _with3 = quote;
                    //设置报价已读状态
                    _with3.QuoteStatus = _with3.QuoteStatus.Remove(2, 1);
                    _with3.QuoteStatus = _with3.QuoteStatus.Insert(2, "1");
                    xpQuote.Update(_with3);


                    XPInquiry upInquiry = new XPInquiry();

                    XPInquiryInfo inquiryInfo = upInquiry.GetXPInquiry(quote.InquiryID);
                    inquiryInfo.InquiryStatus = inquiryInfo.InquiryStatus.Remove(0, 1);
                    inquiryInfo.InquiryStatus = inquiryInfo.InquiryStatus.Insert(0, "1");
                    upInquiry.Update(inquiryInfo);
                    //发送系统邮件给报价供应商


                }

            }
            catch (Exception ex)
            {
                return -1;

            }

            return 1;
        }


        /// <summary>
        /// 询盘审核
        /// </summary>
        /// <returns></returns>
        /// <remarks></remarks>
        public static int ModerateInquiry(string loginUser, Guid inquiryId, InquiryStatus action)
        {

            MembershipUser moderateuser = default(MembershipUser);

            //moderateuser = Membership.GetUser("xelor@test.com");
            moderateuser = Membership.GetUser(loginUser);
            if (moderateuser == null)
            {
                return -1;
            }
            else
            {
                try
                {
                    XPInquiry upInquiry = new XPInquiry();

                    XPInquiryInfo inquiryInfo = upInquiry.GetXPInquiry(inquiryId);
                    var _with1 = inquiryInfo;
                    //设置询盘审核状态
                    _with1.ModerationDate = DateTime.Now;
                    _with1.ModerationUserID = (Guid)moderateuser.ProviderUserKey;
                    _with1.InquiryStatus = _with1.InquiryStatus.Remove(2, 1);
                    _with1.InquiryStatus = _with1.InquiryStatus.Insert(2, action.GetHashCode().ToString());
                    upInquiry.Update(_with1);

                    return 1;
                }
                catch (Exception ex)
                {
                    return -1;
                }
            }
            //return -1;

        }

        public static int ModerateVendor(string loginUser, Guid companyid, ModerateAction action, string comment)
        {
            MembershipUser moderateuser = default(MembershipUser);
            //moderateuser = Membership.GetUser(HttpContext.Current.User.Identity.Name)
            //moderateuser = Membership.GetUser("xelor@test.com");
            moderateuser = Membership.GetUser(loginUser);
            if (moderateuser == null)
            {
                return -1;
            }
            else
            {
                int result = 0;
                SqlCommand command = new SqlCommand("[dbo].[xunpan_XPModerateVendor]", new SqlConnection(GlobalSetting.ConnectionString));
                command.CommandType = CommandType.StoredProcedure;

                command.Parameters.Add(new SqlParameter("ReturnValue ", SqlDbType.Int, 4, ParameterDirection.ReturnValue, false, 0, 0, string.Empty, DataRowVersion.Default, null));
                command.Parameters.Add(new SqlParameter("CompanyID", companyid));
                command.Parameters.Add(new SqlParameter("VendorModerateDate", SqlDbType.DateTime));
                command.Parameters.Add(new SqlParameter("VendorModerateUser", SqlDbType.UniqueIdentifier));
                command.Parameters.Add(new SqlParameter("VendorModerateStatus", SqlDbType.SmallInt));
                command.Parameters.Add(new SqlParameter("ModerateComment", comment));
                command.Parameters["VendorModerateDate"].Value = DateTime.Now;
                command.Parameters["VendorModerateUser"].Value = moderateuser.ProviderUserKey;
                command.Parameters["VendorModerateStatus"].Value = action;

                command.Connection.Open();
                command.ExecuteNonQuery();
                command.Connection.Close();

                result = Convert.ToInt32(command.Parameters["ReturnValue "].Value);
                return result;
            }

            //return -1;
        }


        public static int ModerateBuyer(string loginUser, Guid companyid, ModerateAction action, string comment)
        {
            MembershipUser moderateuser = default(MembershipUser);
            //moderateuser = Membership.GetUser(HttpContext.Current.User.Identity.Name)
            //moderateuser = Membership.GetUser("xelor@test.com");
            moderateuser = Membership.GetUser(loginUser);
            if (moderateuser == null)
            {
                return -1;
            }
            else
            {
                int result = 0;
                SqlCommand command = new SqlCommand("[dbo].[xunpan_XPModerateBuyer]", new SqlConnection(GlobalSetting.ConnectionString));
                command.CommandType = CommandType.StoredProcedure;

                command.Parameters.Add(new SqlParameter("ReturnValue ", SqlDbType.Int, 4, ParameterDirection.ReturnValue, false, 0, 0, string.Empty, DataRowVersion.Default, null));
                command.Parameters.Add(new SqlParameter("CompanyID", companyid));
                command.Parameters.Add(new SqlParameter("BuyerModerateDate", SqlDbType.DateTime));
                command.Parameters.Add(new SqlParameter("BuyerModerateUser", SqlDbType.UniqueIdentifier));
                command.Parameters.Add(new SqlParameter("BuyerModerateStatus", SqlDbType.SmallInt));
                command.Parameters.Add(new SqlParameter("ModerateComment", comment));
                command.Parameters["BuyerModerateDate"].Value = DateTime.Now;
                command.Parameters["BuyerModerateUser"].Value = moderateuser.ProviderUserKey;
                command.Parameters["BuyerModerateStatus"].Value = action;

                command.Connection.Open();
                command.ExecuteNonQuery();
                command.Connection.Close();

                result = Convert.ToInt32(command.Parameters["ReturnValue "].Value);
                return result;
            }
            //return -1;
        }


    }
}
